<template>
  <div class="bid-detail">
    <card style="margin: 0.2rem">
      <div class="van-hairline--bottom headTitle">
        <van-icon name="arrow-left" @click="back" />
        {{ title }}
      </div>
      <van-skeleton title :row="5" :loading="loading">
        <van-form ref="form" @submit="formSubmited">
          <!-- <van-field
            v-model="form.serialNum"
            name="serialNum"
            label="编号"
            placeholder="保存后自动生成编号"
            disabled
            v-show="pageType == 1"
          />-->

          <van-field
            v-model="showForm.cusAddDocumentId_show"
            name="cusAddDocumentId"
            label="客户名称"
            placeholder="请选择客户名称"
            required
            readonly
            clickable
            :rules="[
              { validator: cusAddDocsValidate, message: '请输入正确内容' },
            ]"
            :disabled="!canEdit"
            @click="openFuzzyPopup('cusAddDocumentId', 'cusFullName')"
          />
          <van-popup
            v-model="popupVisible"
            position="top"
            @opened="fuzzyPopupOpened"
          >
            <div class="salesmanPopupContainer">
              <van-search
                ref="popupDom"
                v-model="searchValue"
                placeholder="请输入搜索关键词"
                :show-action="showSearchAdd"
                @input="fuzzyInput"
                @clear="fuzzyClear"
              >
                <template #action>
                  <div @click="fuzzyAdd" style="color: #1989fa">添加/修改</div>
                </template>
              </van-search>
              <div class="salesmanItemContainer">
                <div
                  v-for="item in searchArray"
                  :key="'' + item.id + Math.random()"
                  @click="fuzzyItemClick(item)"
                  class="salesmanItem van-hairline--bottom"
                >
                  {{ item[popupCtr.showKey] }}
                </div>
              </div>
            </div>
          </van-popup>

          <van-field
            v-model="showForm.projectReportId_show"
            name="projectReportId"
            label="项目名称"
            placeholder="请选择项目名称"
            required
            readonly
            clickable
            :rules="[
              { validator: projectReportIdValidate, message: '请输入正确内容' },
            ]"
            :disabled="!canEdit"
            @click="openFuzzyPopup('projectReportId', 'projectName', true)"
          />

          <van-field
            v-model="form.tenderer"
            name="tenderer"
            label="招标人"
            placeholder="请输入招标人"
            :disabled="!canEdit"
          />

          <van-field
            v-model="form.bidAmount"
            name="bidAmount"
            label="投标金额"
            type="number"
            required
            placeholder="请输入投标金额"
            :disabled="!canEdit"
          />

          <van-field
            v-model="form.detailAddress"
            name="detailAddress"
            label="详细地址"
            type="textarea"
            placeholder="请输入详细地址"
            :disabled="!canEdit"
          />

          <van-field
            v-model="showForm.salesmanId_show"
            name="salesmanId"
            label="跟进业务员"
            placeholder="请选择跟进业务员"
            required
            readonly
            clickable
            :rules="[
              { validator: salesmanValidate, message: '请输入正确内容' },
            ]"
            :disabled="!canEdit"
            @click="openFuzzyPopup('salesmanId', 'nickName')"
          />

          <van-field
            v-model="form.chargeBidManager"
            name="chargeBidManager"
            label="招标联系人"
            placeholder="请输入招标联系人"
            :disabled="!canEdit"
          />

          <van-field
            v-model="form.bidContactInfo"
            name="bidContactInfo"
            label="招标联系方式"
            placeholder="请输入招标联系方式"
            :disabled="!canEdit"
          />

          <van-field
            v-model="form.margin"
            name="margin"
            label="投标保证金"
            placeholder="请输入投标保证金"
            :disabled="!canEdit"
          />

          <van-field
            readonly
            clickable
            name="tenderInDate"
            :value="form.tenderInDate"
            label="截标时间"
            placeholder="点击选择日期"
            :disabled="!canEdit"
            @click="canEdit ? (tenderInDateShow = true) : null"
          />

          <van-field
            name="subjectContract"
            label="签约合同主体"
            required
            :disabled="!canEdit"
            :rules="[
              {
                required: true,
                message: '请选择签约合同主体',
                trigger: 'onChange',
              },
            ]"
          >
            <template #input>
              <van-radio-group
                v-model="form.subjectContract"
                direction="horizontal"
                :disabled="!canEdit"
              >
                <van-radio
                  v-for="item in subjectContractDict"
                  :key="item.value"
                  :name="item.value"
                  >{{ item.text }}</van-radio
                >
              </van-radio-group>
            </template>
          </van-field>

          <van-field
            v-model="form.agentName"
            name="agentName"
            label="代理商"
            placeholder="请输入代理商"
            :rules="[{ validator: agentNameValid, message: '请输入代理商' }]"
            :disabled="!canEdit"
          />

          <van-field
            name="winBidCase"
            label="中标情况"
            required
            :disabled="!canEdit || !bidMsgCanEdit"
            :rules="[
              {
                required: true,
                message: '请选择中标情况',
                trigger: 'onChange',
              },
            ]"
          >
            <template #input>
              <van-radio-group
                v-model="form.winBidCase"
                direction="horizontal"
                :disabled="!canEdit || !bidMsgCanEdit"
              >
                <van-radio :name="'1'">中标</van-radio>
                <van-radio :name="'2'">丢标</van-radio>
              </van-radio-group>
            </template>
          </van-field>

          <van-field
            readonly
            clickable
            name="winBidDate"
            :value="form.winBidDate"
            label="中标丢标时间"
            placeholder="点击选择日期"
            :disabled="!canEdit"
            :rules="[{ validator: winBidDateValidate, message: '请选择时间' }]"
            required
            @click="canEdit && (winBidDateShow = true)"
          />

          <van-field
            v-model="form.loseBidReason"
            name="loseBidReason"
            label="丢标原因分析"
            placeholder="请输入丢标原因分析"
            type="textarea"
            autosize
            :rules="[
              { validator: loseBidReasonVali, message: '请输入丢标原因分析' },
            ]"
            :disabled="!canEdit"
          />

          <van-field
            name="purchaseForm"
            label="采购形式"
            required
            :rules="[
              {
                required: true,
                message: '请选择采购形式',
                trigger: 'onChange',
              },
            ]"
            :disabled="!canEdit"
          >
            <template #input>
              <van-radio-group
                v-model="form.purchaseForm"
                direction="horizontal"
                :disabled="!canEdit"
              >
                <van-radio
                  :name="item.value"
                  v-for="item in purchaseFormDict"
                  :key="item.value"
                  >{{ item.text }}</van-radio
                >
              </van-radio-group>
            </template>
          </van-field>

          <van-field
            v-model="form.remark"
            name="remark"
            label="备注"
            placeholder="请输入备注"
            type="textarea"
            autosize
            :disabled="!canEdit"
          />

          <van-field readonly label="型号">
            <template #button>
              <van-button
                size="small"
                type="primary"
                native-type="button"
                :disabled="!canEdit"
                @click="openLockModal(undefined)"
                >添加型号</van-button
              >
            </template>
          </van-field>

          <v-table
            is-horizontal-resize
            style="width: 100%"
            :columns="lockModalCol"
            :table-data="lockModelArr"
            row-hover-color="#eee"
            row-click-color="#edf7ff"
            :row-click="lockItemClick"
          ></v-table>
        </van-form>
        <div style="margin: 0.3rem" v-if="recordCanEdit">
          <van-row type="flex">
            <van-col class="bottomBtnCol" v-if="pageType == 1">
              <van-button
                round
                block
                type="default"
                native-type="button"
                @click="canEditBtnClick"
                >{{ canEdit ? "取消" : "编辑" }}</van-button
              >
            </van-col>
            <van-col class="bottomBtnCol">
              <van-button
                round
                block
                type="info"
                native-type="button"
                :disabled="!canEdit"
                @click="okBtnClick"
                >确定</van-button
              >
            </van-col>
          </van-row>
        </div>
      </van-skeleton>
    </card>

    <van-popup v-model="lockModalVisible" :close-on-click-overlay="false">
      <div class="lockModalContainer">
        <div class="lockModalTitle">{{ lockModalTitle }}</div>
        <van-form ref="lockForm" @submit="lockFormSubmit">
          <van-field
            v-model="lockPopop.model"
            label="型号"
            required
            :rules="[{ required: true, message: '请输入型号' }]"
            placeholder="请输入型号"
          />
          <van-field
            v-model="lockPopop.quantity"
            label="数量（套）"
            :rules="[{ required: true, message: '请输入数量' }]"
            required
            placeholder="请输入数量（套）"
          />
          <van-field
            v-model="lockPopop.price"
            label="价格"
            required
            type="number"
            :rules="[{ required: true, message: '请输入价格' }]"
            placeholder="请输入价格"
          />
          <van-field
            v-model="lockPopop.color"
            label="颜色"
            required
            placeholder="请输入颜色"
            :rules="[{ required: true, message: '请输入颜色' }]"
          />
          <van-field
            readonly
            clickable
            :value="lockPopop.estimateInstallYear"
            label="预计交楼年份"
            placeholder="点击选择预计交楼年份"
            required
            :rules="[{ required: true, message: '请输入预计交楼年份' }]"
            @click="showYearPicker = true"
          />
          <van-field
            readonly
            clickable
            name="estimateInstallYear"
            :value="lockPopop.estimateInstallMonth"
            label="预计交楼月份"
            placeholder="点击选择预计交楼月份"
            required
            :rules="[{ required: true, message: '请输入预计交楼月份' }]"
            @click="showMonthPicker = true"
          />
          <van-field
            v-model="lockPopop.productFunction"
            label="产品功能要求"
            required
            placeholder="请输入产品功能要求"
            :rules="[{ required: true, message: '请输入颜色' }]"
          />
          <van-field
            readonly
            clickable
            name="winBidDate"
            :value="lockPopop.winBidDate"
            label="时间"
            placeholder="点击选择时间"
            required
            :rules="[{ required: true, message: '请输入时间' }]"
            @click="lockWinBidDateShow = true"
          />
        </van-form>

        <van-row type="flex" justify="end" class="lockModalBtnContainer">
          <van-button
            size="small"
            class="lockModalBtn"
            @click="lockModalVisible = false"
            >关闭</van-button
          >
          <van-button
            size="small"
            type="danger"
            class="lockModalBtn"
            :disabled="lockCurIndex == -1"
            @click="deleteLockItem"
            >删除</van-button
          >
          <van-button
            size="small"
            type="info"
            class="lockModalBtn"
            @click="lockModalValid"
            >保存</van-button
          >
        </van-row>
      </div>
    </van-popup>

    <van-popup :lazy-render="false" v-model="showYearPicker" position="bottom">
      <van-picker
        ref="yearPicker"
        show-toolbar
        :columns="yearArr"
        :default-index="lockDefaultYearIndex"
        @confirm="yearConfirm"
        @cancel="showYearPicker = false"
      />
    </van-popup>
    <van-popup :lazy-render="false" v-model="showMonthPicker" position="bottom">
      <van-picker
        ref="monthPicker"
        show-toolbar
        :columns="monthArr"
        @confirm="monthConfirm"
        @cancel="showMonthPicker = false"
      />
    </van-popup>

    <van-calendar
      ref="tenderInDateCalendar"
      v-model="tenderInDateShow"
      :default-date="tenderInDateShowDefaultDate"
      :min-date="minDate"
      :max-date="maxDate"
      @confirm="tenderInDateShowConfirm"
    />
    <van-calendar
      ref="winBidDateCalendar"
      v-model="winBidDateShow"
      :default-date="winBidDateShowDefaultDate"
      :min-date="minDate"
      :max-date="maxDate"
      @confirm="winBidDateConfirm"
    />
    <van-calendar
      ref="lockWinBidDateCalendar"
      v-model="lockWinBidDateShow"
      :default-date="lockWinBidDateShowDefaultDate"
      :min-date="minDate"
      :max-date="maxDate"
      @confirm="lockWinBidDateConfirm"
    />
  </div>
</template>

<script>
import Card from "@/components/Card";
import { _purchaseFormDict, _subjectContractDict } from "@/utils/dict";
import { mapActions, mapMutations } from "vuex";
import {
  Skeleton,
  Form,
  Field,
  Picker,
  Calendar,
  RadioGroup,
  Radio,
  Popup,
  Button,
  Search,
  NumberKeyboard,
  Toast,
  Row,
  Col,
  Icon,
} from "vant";
import Fuse from "fuse.js";
import { formatDate } from "@/utils";
import _ from "lodash";
export default {
  components: {
    Card,
    [Skeleton.name]: Skeleton,
    [Form.name]: Form,
    [Field.name]: Field,
    [Picker.name]: Picker,
    [Calendar.name]: Calendar,
    [RadioGroup.name]: RadioGroup,
    [Radio.name]: Radio,
    [Popup.name]: Popup,
    [Button.name]: Button,
    [Search.name]: Search,
    [NumberKeyboard.name]: NumberKeyboard,
    [Row.name]: Row,
    [Col.name]: Col,
    [Icon.name]: Icon,
  },
  data() {
    return {
      title: "",
      pageType: 0,
      loading: false,
      form: {
        serialNum: "",
        tenderer: "",
        bidAmount: "",
        detailAddress: "",
        bidManager: "",
        chargeBidManager: "",
        bidContactInfo: "",
        margin: "",
        tenderInDate: "",
        winBidCase: "",
        winBidDate: "",
        purchaseForm: "",
        loseBidReason: "",
        remark: "",
        cusAddDocumentId: "",
        projectReportId: "",
        salesmanId: "",
        lockModel: "",
        subjectContract: "",
        agentName: "",
      },
      // 表单项展示用数据
      showForm: {
        cusAddDocumentId_show: "",
        salesmanId_show: "",
        projectReportId_show: "",
      },
      // 模糊搜索用弹窗控制
      popupCtr: {
        formName: "",
        showKey: "",
      },
      searchValue: "",
      popupVisible: false,
      searchArray: [],
      showSearchAdd: false,

      purchaseFormDict: _purchaseFormDict,
      subjectContractDict: _subjectContractDict,

      salesmanIdArrOrigin: [],
      cusAddDocumentIdArrOrigin: [],
      projectReportIdArrOrigin: [],
      // 送样型号相关参数
      lockModalVisible: false,
      lockModalTitle: "",

      lockPopop: {
        model: "",
        quantity: "",
        price: "",
        product: "",
        color: "",
        id:"",
        estimateInstallYear: "",
        estimateInstallMonth: "",
        productFunction: "",
        winBidDate: "",
      },
      lockCurIndex: -1,
      lockDefaultYearIndex: 0,

      tenderInDateShow: false,
      tenderInDateShowDefaultDate: new Date(),
      winBidDateShow: false,
      winBidDateShowDefaultDate: new Date(),
      lockWinBidDateShow: false,
      lockWinBidDateShowDefaultDate: new Date(),
      minDate: new Date("2000/01/01"),
      maxDate: new Date("2100/01/01"),

      showYearMonthPicker: false,
      showYearPicker: false,
      yearArr: _.range(2010, 2100),
      showMonthPicker: false,
      monthArr: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],

      // 样品型号和竞品列表数组
      lockModelArr: [],
      lockModelArrOrigin: [],

      lockModalCol: [
        {
          field: "model",
          title: "型号",
          titleAlign: "center",
          columnAlign: "center",
          isResize: true,
          width: 30,
        },
        {
          field: "quantity",
          title: "数量（套）",
          titleAlign: "center",
          columnAlign: "center",
          isResize: true,
          width: 30,
        },
        {
          field: "price",
          title: "价格",
          titleAlign: "center",
          columnAlign: "center",
          isResize: true,
          width: 30,
        },
        {
          field: "color",
          title: "颜色",
          titleAlign: "center",
          columnAlign: "center",
          isResize: true,
          width: 30,
        },
      ],
      canEdit: false,
      recordCanEdit: true, // 作废或者审批拒绝则不能编辑
      bidMsgCanEdit: true,
    };
  },
  watch: {
    "form.winBidCase"(val) {
      if (val == "1") {
        this.$refs.form.resetValidation("loseBidReason");
      }
    },
  },
  created() {
    if (this.$route.query.type == "add") {
      this.title = "添加投标";
      document.title = "添加投标";
      this.pageType = 0;
      this.canEdit = true;
    } else {
      this.title = "编辑投标";
      document.title = "编辑投标";
      this.pageType = 1;
    }
  },
  mounted() {
    this.loading = true;
    this.initData();
    this.resetLockPopop();
  },
  beforeDestroy() {
    this.resetDocsDetail();
  },
  methods: {
    ...mapActions({
      getCusDocsList: "projectReport/getCusDocsList",
      querySalesman: "cusAddDocs/querySalesman",
      getProjectListByCusId: "bid/getProjectListByCusId",
      getLockModal: "bid/getLockModal",
      addBid: "bid/addBid",
      updateBid: "bid/updateBid",
    }),
    ...mapMutations({
      resetDocsDetail: "bid/resetDocsDetail",
    }),
    initData() {
      let detail = this.$store.state.bid.docsDetail;
      if (this.pageType == 1) {
        // this.recordCanEdit = false;
        this.bidMsgCanEdit = false;
      }
      for (const key in detail) {
        if (detail.hasOwnProperty(key)) {
          const element = detail[key];
          this.form[key] = "" + element;
        }
      }
      Promise.all([this.getCusDocsList(), this.querySalesman()])
        .then((res) => {
          console.log(res);
          // this.salesmanArr = res[1].data;
          let salesmanArr = res[1].data;
          let cusArr = res[0].data;
          if (salesmanArr.length) {
            this.salesmanIdArrOrigin = JSON.parse(JSON.stringify(salesmanArr));
            if (this.pageType == 1) {
              for (let i = 0, len = salesmanArr.length; i < len; i++) {
                if (salesmanArr[i].id == detail.salesmanId) {
                  this.showForm.salesmanId_show = salesmanArr[i].nickName;
                  break;
                }
              }
            }
          }

          // this.cusAddDocumentIdArr = res[0].data;
          if (cusArr.length) {
            this.cusAddDocumentIdArrOrigin = JSON.parse(JSON.stringify(cusArr));
            if (this.pageType == 1) {
              for (let i = 0, len = cusArr.length; i < len; i++) {
                if (cusArr[i].id == detail.cusAddDocumentId) {
                  this.showForm.cusAddDocumentId_show = cusArr[i].cusFullName;
                  break;
                }
              }
            }
          }
          this.loading = false;
        })
        .catch((err) => {
          console.log(err);
          this.loading = false;
        });

      if (this.pageType == 1 && this.form.id) {
        this.getLockModal({ id: this.form.id })
          .then((res) => {
            console.log(res);
            res.data.forEach((e) => {
              if (e.winBidDate) {
                e.winBidDate = formatDate(new Date(e.winBidDate), "yyyy-MM-dd");
              }
            });
            this.lockModelArr = res.data;
            this.lockModelArrOrigin = JSON.parse(JSON.stringify(res.data));
          })
          .catch((err) => {
            console.log(err);
          });
        this.getProjectListByCusId({
          cusAddDocumentId: this.form.cusAddDocumentId,
        })
          .then((res) => {
            if (res) {
              console.log(res);
              this.projectReportIdArrOrigin = res;
              for (let i = 0, len = res.length; i < len; i++) {
                if (res[i].id == detail.projectReportId) {
                  this.showForm.projectReportId_show = res[i].projectName;
                  break;
                }
              }
            }
          })
          .catch((err) => {
            console.log(err);
          });
        this.$nextTick(() => {
          if (detail.tenderInDate) {
            let date = new Date(detail.tenderInDate);
            this.tenderInDateDefaultDate = date;
            this.$refs.tenderInDateCalendar.reset();
            this.form.tenderInDate = formatDate(date, "yyyy-MM-dd");
          }
          if (detail.winBidDate) {
            let date2 = new Date(detail.winBidDate);
            this.winBidDateShowDefaultDate = date2;
            this.$refs.winBidDateCalendar.reset();
            this.form.winBidDate = formatDate(date2, "yyyy-MM-dd");
          }
        });
      }
    },
    salesmanValidate(val) {
      return this.form.salesmanId ? true : false;
    },
    cusAddDocsValidate(val) {
      return this.form.cusAddDocumentId ? true : false;
    },
    projectReportIdValidate(val) {
      return this.form.projectReportId ? true : false;
    },
    winBidDateValidate(val) {
      return this.form.winBidDate ? true : false;
    },
    loseBidReasonVali(val) {
      return this.form.winBidCase == "2" ? (val ? true : false) : true;
    },
    agentNameValid(val) {
      return this.form.subjectContract == "1" ? true : val ? true : false;
    },
    openFuzzyPopup(formName, showKey, showSearchAdd) {
      if (this.canEdit) {
        this.popupCtr.formName = formName;
        this.popupCtr.showKey = showKey;
        this.searchValue = "";
        this.searchArray = [];
        if (formName == "projectReportId") {
          this.searchValue = this.form.projectName;
        }
        this.popupVisible = true;
        this.showSearchAdd = showSearchAdd;
      }
    },
    fuzzyPopupOpened() {
      let child = this.$refs.popupDom.getElementsByTagName("input");
      child[0].focus();
    },
    fuzzyItemClick(item) {//模糊搜索选项点击
      console.log(item);
      this.form[this.popupCtr.formName] = item.id;
      this.showForm[`${this.popupCtr.formName}_show`] =
        item[this.popupCtr.showKey];
      if (this.popupCtr.formName == "cusAddDocumentId") {
        this.getProjectListByCusId({ cusAddDocumentId: item.id })
          .then((res) => {
            if (res) {
              console.log(res);
              this.projectReportIdArrOrigin = res;
              this.form.projectReportId = "";
              this.showForm.projectReportId_show = "";
            }
          })
          .catch((err) => {
            console.log(err);
          });
      }
      this.popupCtr.formName = "";
      this.popupCtr.showKey = "";
      this.searchValue = "";
      this.searchArray = [];
      this.popupVisible = false;
    },
    fuzzyInput(value) {//模糊搜索输入
      console.log("value", value);
      if (value == "") {
        this.searchArray = [];
      } else {
        const options = {
          includeScore: true,
          // Search in `author` and in `tags` array
          keys: [this.popupCtr.showKey],
        };
        const fuse = new Fuse(
          this[`${this.popupCtr.formName}ArrOrigin`],
          options
        );
        const result = fuse.search(value);
        this.searchArray = [];
        result.forEach((e) => {
          this.searchArray.push(e.item);
        });
      }
    },
    fuzzyClear() {
      console.log("clear");
      this.form[this.popupCtr.formName] = "";
      this.showForm[`${this.popupCtr.formName}_show`] = "";
    },
    fuzzyAdd() {//模糊搜索点添加
      if (this.searchValue) {
        // this.form[this.popupCtr.formName] = this.searchValue;
        if (this.popupCtr.formName == "projectReportId") {
          if (this.form.projectReportId == "") {
            return Toast("请先选择项目");
          }
          this.form.projectName = this.searchValue;
        }
        this.showForm[`${this.popupCtr.formName}_show`] = this.searchValue;
        this.popupVisible = false;
      }
    },
    yearConfirm(value) {
      // 年份确认
      console.log(value);
      this.lockPopop.estimateInstallYear = value;
      this.showYearPicker = false;
    },
    monthConfirm(value) {
      // 月份确认
      this.lockPopop.estimateInstallMonth = value;
      this.showMonthPicker = false;
    },
    openLockModal(item) {
      // 打开送样型号弹窗
      if (this.canEdit) {
        if (item) {
          this.lockPopop = item;
          this.lockModalTitle = "编辑送样型号";
          if (item.winBidDate) {
            this.lockWinBidDateShowDefaultDate = new Date(item.winBidDate);
            this.$refs.lockWinBidDateCalendar.reset();
          }
        } else {
          this.resetLockPopop();
          if (this.form.winBidDate) {
            this.lockWinBidDateShowDefaultDate = new Date(this.form.winBidDate);
            this.$refs.lockWinBidDateCalendar.reset();
            this.lockPopop.winBidDate = this.form.winBidDate;
          }
          this.lockModalTitle = "添加送样型号";
        }
        this.lockModalVisible = true;
      }
    },
    tenderInDateShowConfirm(date) {
      this.form.tenderInDate = formatDate(date, "yyyy-MM-dd");
      this.tenderInDateShow = false;
    },
    winBidDateConfirm(date) {
      this.form.winBidDate = formatDate(date, "yyyy-MM-dd");
      this.winBidDateShow = false;
    },
    lockWinBidDateConfirm(date) {
      this.lockPopop.winBidDate = formatDate(date, "yyyy-MM-dd");
      this.lockWinBidDateShow = false;
    },
    lockFormSubmit() {
      this.saveLockModel();
    },
    lockModalValid() {
      this.$refs.lockForm.submit();
    },
    saveLockModel() {
      // 送样型号保存点击
      let obj = JSON.parse(JSON.stringify(this.lockPopop));
      if (this.lockCurIndex == -1) {
        this.lockModelArr.push(obj);
      } else {
        this.$set(this.lockModelArr, this.lockCurIndex, obj);
      }

      this.lockModalVisible = false;
    },
    resetLockPopop() {
      // 重置送样型号相关信息
      this.lockPopop = {
        model: "",
        quantity: "",
        price: "",
        product: "",
        color: "",
        id:"",
        estimateInstallYear: "",
        estimateInstallMonth: "",
        productFunction: "",
      };
      this.lockCurIndex = -1;
    },
    deleteLockItem() {
      //删除送样型号
      if (this.lockCurIndex > -1) {
        this.$delete(this.lockModelArr, this.lockCurIndex);
        this.lockModalVisible = false;
      }
    },
    lockItemClick(rowIndex, rowData, column) {
      // 送样型号表格项点击
      console.log(rowIndex, rowData, column);
      this.lockCurIndex = rowIndex;
      this.openLockModal(JSON.parse(JSON.stringify(rowData)));
    },
    canEditBtnClick() {
      if (this.canEdit) {
        // 取消 还原数据
        this.form = {
          serialNum: "",
          tenderer: "",
          bidAmount: "",
          detailAddress: "",
          bidManager: "",
          chargeBidManager: "",
          bidContactInfo: "",
          margin: "",
          tenderInDate: "",
          winBidCase: "",
          winBidDate: "",
          purchaseForm: "",
          loseBidReason: "",
          remark: "",
          cusAddDocumentId: "",
          projectReportId: "",
          salesmanId: "",
          lockModel: "",
          subjectContract: "",
          agentName: "",
        };

        let detail = this.$store.state.bid.docsDetail;
        for (const key in detail) {
          if (detail.hasOwnProperty(key)) {
            const element = detail[key];
            this.form[key] = "" + element;
          }
        }
        if (detail.tenderInDate) {
          let date = new Date(detail.tenderInDate);
          this.tenderInDateDefaultDate = date;
          this.$refs.tenderInDateCalendar.reset();
          this.form.tenderInDate = formatDate(date, "yyyy-MM-dd");
        }
        if (detail.winBidDate) {
          let date2 = new Date(detail.winBidDate);
          this.winBidDateShowDefaultDate = date2;
          this.$refs.winBidDateCalendar.reset();
          this.form.winBidDate = formatDate(date2, "yyyy-MM-dd");
        }

        let salesmanArr = this.salesmanIdArrOrigin;
        for (let i = 0, len = salesmanArr.length; i < len; i++) {
          if (salesmanArr[i].id == detail.salesmanId) {
            this.showForm.salesmanId_show = salesmanArr[i].nickName;
            break;
          }
        }
        let cusArr = this.cusAddDocumentIdArrOrigin;
        for (let i = 0, len = cusArr.length; i < len; i++) {
          if (cusArr[i].id == detail.cusAddDocumentId) {
            this.showForm.cusAddDocumentId_show = cusArr[i].cusFullName;
            break;
          }
        }

        this.lockModelArr = JSON.parse(JSON.stringify(this.lockModelArrOrigin));
      }
      this.canEdit = !this.canEdit;
    },
    okBtnClick() {
      this.$refs.form.submit();
    },
    back() {
      this.$router.go(-1);
    },
    formSubmited() {
      if (this.lockModelArr.length == 0) {
        return Toast("送样型号不能为空");
      }
      if (this.pageType == 0) {
        let lockModelStr = JSON.stringify(this.lockModelArr);
        this.form.lockModel = lockModelStr;
        console.log(this.form);
        this.addBid(this.form)
          .then((res) => {
            console.log(res);
            if (res.success) {
              Toast.success("新建成功");
              this.$router.go(-1);
            } else {
              Toast.fail(`新建失败：${res.message}`);
            }
          })
          .catch((err) => {
            console.log(err);
          });
      } else {
        let lockModelStr = JSON.stringify(this.lockModelArr);
        this.form.lockModel = lockModelStr;

        this.updateBid(this.form)
          .then((res) => {
            console.log(res);
            if (res.success) {
              Toast.success("更新成功");
              // this.$router.go(-1);
            } else {
              Toast.fail(`更新失败：${res.message}`);
            }
          })
          .catch((err) => {
            console.log(err);
          });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.bid-detail {
  background-image: linear-gradient(rgb(216, 231, 240), white);
  padding: 12px;
  .headTitle {
    font-size: 24px;
    padding-bottom: 12px;
    align-items: center;
    display: flex;
  }
  .van-radio {
    margin-bottom: 8px;
  }
  .salesmanPopupContainer {
    max-height: 100vh;
    overflow: hidden;
    .salesmanItemContainer {
      overflow: auto;
      position: relative;
      max-height: 600px;
      .salesmanItem {
        padding: 8px 12px;
      }
    }
  }
  .lockModalContainer {
    width: 320px;
    .lockModalTitle {
      padding: 8px 8px 8px 12px;
      font-size: 20px;
    }
    .lockModalBtnContainer {
      margin: 8px;
      .lockModalBtn {
        margin-left: 8px;
      }
    }
  }
  .bottomBtnCol {
    flex: 1;
    padding: 8px;
  }
}
</style>